<template>
  <div class="arbitrage-page">
    <!-- 第一行：策略选择 + 价格监控 -->
    <el-row :gutter="20">
      <!-- 左侧：策略选择和分析 -->
      <el-col :span="8">
        <el-card class="strategy-card">
          <template #header>
            <div class="strategy-header">
              <h3>📈 套利策略选择</h3>
              <el-tag :type="getStrategyTagType(selectedStrategy)">
                {{ getStrategyAnalysis(selectedStrategy).name }}
              </el-tag>
            </div>
          </template>
          
          <!-- 策略选择器 -->
          <div class="strategy-selector">
            <el-radio-group v-model="selectedStrategy" @change="onStrategyChange" class="horizontal-radio-group">
              <el-radio-button 
                v-for="strategy in Object.values(ArbitrageStrategy)" 
                :key="strategy"
                :label="strategy"
                :class="getStrategyClass(strategy)"
              >
                {{ getStrategyName(strategy) }}
              </el-radio-button>
            </el-radio-group>
          </div>

          <!-- 策略分析 -->
          <div class="strategy-analysis">
            <div class="metrics-row">
              <div class="metric">
                <span class="label">风险等级</span>
                <el-tag :type="getRiskTagType(currentAnalysis.riskLevel)">
                  {{ getRiskLevelText(currentAnalysis.riskLevel) }}
                </el-tag>
              </div>
              <div class="metric">
                <span class="label">利润潜力</span>
                <el-tag :type="getProfitTagType(currentAnalysis.profitPotential)">
                  {{ getProfitPotentialText(currentAnalysis.profitPotential) }}
                </el-tag>
              </div>
            </div>
            
            <div class="metrics-row">
              <div class="metric">
                <span class="label">执行复杂度</span>
                <el-rate
                  :model-value="getComplexityRate(currentAnalysis.executionComplexity)"
                  disabled
                  show-score
                  text-color="#ff9900"
                />
              </div>
            </div>

            <div class="recommendation">
              <strong>推荐对象：</strong>{{ currentAnalysis.recommendedFor }}
            </div>

            <!-- 优劣势对比 -->
            <el-row :gutter="10" class="pros-cons">
              <el-col :span="12">
                <div class="pros">
                  <h4>✅ 优势</h4>
                  <ul>
                    <li v-for="pro in currentAnalysis.pros" :key="pro">{{ pro }}</li>
                  </ul>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="cons">
                  <h4>❌ 劣势</h4>
                  <ul>
                    <li v-for="con in currentAnalysis.cons" :key="con">{{ con }}</li>
                  </ul>
                </div>
              </el-col>
            </el-row>

            <!-- 适用交易所 -->
            <div class="strategy-exchanges">
              <h4>🏦 适用交易所 ({{ getFilteredExchanges().length }}个)</h4>
              <p style="font-size: 12px; color: #6b7280; margin: 0 0 12px 0;">
                根据选择的策略自动筛选相关交易所
              </p>
              <div class="exchanges-grid">
                <div 
                  v-for="exchange in getFilteredExchanges()" 
                  :key="exchange.id"
                  :class="['strategy-exchange-item', exchange.type.toLowerCase()]"
                >
                  <div class="exchange-header">
                    <strong>{{ exchange.name }}</strong>
                    <el-tag :type="exchange.type === 'CEX' ? 'success' : 'warning'" size="small">
                      {{ exchange.type }}
                    </el-tag>
                  </div>
                  <div class="exchange-details">
                    <div class="fee-info">
                      <span class="fee-item">手续费: {{ (exchange.fees.taker * 100).toFixed(3) }}%</span>
                      <span v-if="exchange.fees.gas" class="fee-item">Gas: ${{ exchange.fees.gas }}</span>
                    </div>
                    <div class="characteristics">
                      <el-tag size="small" effect="plain" :type="getCharacteristicTagType(exchange.characteristics.liquidity)">
                        {{ getCharacteristicText(exchange.characteristics.liquidity) }}流动性
                      </el-tag>
                      <el-tag size="small" effect="plain" :type="getCharacteristicTagType(exchange.characteristics.slippage)">
                        {{ getCharacteristicText(exchange.characteristics.slippage) }}滑点
                      </el-tag>
                      <el-tag size="small" effect="plain" :type="getCharacteristicTagType(exchange.characteristics.speed)">
                        {{ getCharacteristicText(exchange.characteristics.speed) }}速度
                      </el-tag>
                    </div>
                    <div v-if="exchange.network" class="networks">
                      <span class="network-label">网络:</span>
                      <el-tag 
                        size="small" 
                        :type="getNetworkTagType(exchange.network)"
                        effect="plain"
                      >
                        {{ exchange.network }}
                      </el-tag>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 最佳实践 -->
            <div class="best-practices">
              <h4>💡 最佳实践</h4>
              <ul>
                <li v-for="practice in currentAnalysis.bestPractices" :key="practice">
                  {{ practice }}
                </li>
              </ul>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 右侧：实时价格监控 -->
      <el-col :span="16">
        <el-card class="price-monitor-card">
          <template #header>
            <div class="monitor-header">
              <h3>📊 实时价格监控</h3>
              <div class="monitor-controls">
                <!-- 交易对选择器 -->
                <el-select 
                  v-model="selectedSymbol" 
                  placeholder="选择交易对" 
                  size="small"
                  style="width: 140px; margin-right: 10px;"
                  @change="onSymbolChange"
                >
                  <el-option 
                    v-for="symbol in availableSymbols" 
                    :key="symbol"
                    :label="symbol" 
                    :value="symbol"
                  />
                </el-select>
                <!-- 轮播控制 -->
                <el-button-group size="small" style="margin-right: 10px;">
                  <el-button @click="prevSymbol" :disabled="availableSymbols.length <= 1">
                    <el-icon><ArrowLeft /></el-icon>
                  </el-button>
                  <el-button @click="nextSymbol" :disabled="availableSymbols.length <= 1">
                    <el-icon><ArrowRight /></el-icon>
                  </el-button>
                </el-button-group>
                <el-switch
                  v-model="symbolAutoSwitch"
                  active-text="自动轮播"
                  size="small"
                  style="margin-right: 10px;"
                  @change="toggleSymbolAutoSwitch"
                />
                <el-switch
                  v-model="autoUpdate"
                  active-text="自动更新"
                  size="small"
                  @change="toggleAutoUpdate"
                />
                <el-button 
                  @click="updateData" 
                  :loading="updating"
                  type="primary" 
                  size="small"
                >
                  刷新数据
                </el-button>
              </div>
            </div>
          </template>

          <div class="price-monitor">
            <!-- 交易对指示器 -->
            <div class="symbol-indicators">
              <div 
                v-for="symbol in availableSymbols" 
                :key="symbol"
                :class="['symbol-indicator', { active: symbol === selectedSymbol }]"
                @click="selectSymbol(symbol)"
              >
                {{ symbol }}
              </div>
            </div>

            <!-- 当前选中交易对的价格数据 -->
            <div class="current-symbol-monitor">
              <h4 class="symbol-title">{{ selectedSymbol }}</h4>
              <div class="exchanges-grid">
                <div 
                  v-for="(data, exchangeName) in getCurrentSymbolData()?.exchanges || {}" 
                  :key="exchangeName"
                  :class="[
                    'exchange-card', 
                    String(exchangeName) === getCurrentSymbolData()?.priceDiff.highestExchange ? 'highest' : '',
                    String(exchangeName) === getCurrentSymbolData()?.priceDiff.lowestExchange ? 'lowest' : '',
                    data.type.toLowerCase()
                  ]"
                >
                  <div class="exchange-name">
                    {{ exchangeName }}
                    <el-tag :type="(data.type === ExchangeType.CEX) ? 'success' : 'warning'" size="small">
                      {{ data.type }}
                    </el-tag>
                    <span v-if="data.network" class="network">{{ data.network }}</span>
                  </div>
                  <div class="price-info">
                    <div class="main-price">${{ data.price.toFixed(2) }}</div>
                    <div class="bid-ask">
                      <span class="bid">买: ${{ data.bid.toFixed(2) }}</span>
                      <span class="ask">卖: ${{ data.ask.toFixed(2) }}</span>
                    </div>
                    <div class="spread">
                      价差: ${{ (data.ask - data.bid).toFixed(2) }} 
                      ({{ (((data.ask - data.bid) / data.price) * 100).toFixed(3) }}%)
                    </div>
                  </div>
                  <div class="volume">24h: ${{ formatNumber(data.volume24h) }}</div>
                  <div class="depth">
                    深度: {{ data.depth.bidQty.toFixed(1) }} / {{ data.depth.askQty.toFixed(1) }}
                  </div>
                </div>
              </div>
              
              <div v-if="getCurrentSymbolData()" class="price-diff-summary">
                <div class="diff-item">
                  <span class="label">显示价差:</span>
                  <span class="value">${{ getCurrentSymbolData()!.priceDiff.maxDiff.toFixed(2) }} ({{ getCurrentSymbolData()!.priceDiff.maxDiffPercent.toFixed(3) }}%)</span>
                </div>
                <div class="diff-item important">
                  <span class="label">真实套利空间:</span>
                  <span class="value">${{ getCurrentSymbolData()!.priceDiff.realSpread.toFixed(2) }} ({{ getCurrentSymbolData()!.priceDiff.spreadPercent.toFixed(3) }}%)</span>
                </div>
                <div class="diff-item">
                  <span class="label">最高价:</span>
                  <span class="value">{{ getCurrentSymbolData()!.priceDiff.highestExchange }}</span>
                </div>
                <div class="diff-item">
                  <span class="label">最低价:</span>
                  <span class="value">{{ getCurrentSymbolData()!.priceDiff.lowestExchange }}</span>
                </div>
                <div class="diff-explanation">
                  <small>
                    真实套利 = {{ getCurrentSymbolData()!.priceDiff.highestExchange }}开空单 + {{ getCurrentSymbolData()!.priceDiff.lowestExchange }}开多单
                  </small>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 第二行：套利机会识别 - 单独占满一行 -->
    <el-row style="margin-top: 20px;">
      <el-col :span="24">
        <el-card class="opportunities-card">
          <template #header>
            <div class="opportunities-header">
              <h3>⚡ 套利机会识别</h3>
              <div class="header-controls">
                <el-tag type="success">{{ filteredOpportunities.filter(o => o.status === 'active').length }} 个活跃</el-tag>
                <el-tag type="info">{{ filteredOpportunities.length }} 个总计</el-tag>
                <!-- 轮播控制 -->
                <el-button-group size="small" style="margin: 0 10px;">
                  <el-button @click="prevOpportunityPage" :disabled="currentOpportunityPage === 0">
                    <el-icon><ArrowLeft /></el-icon>
                  </el-button>
                  <el-button @click="nextOpportunityPage" :disabled="(currentOpportunityPage + 1) * opportunitiesPerPage >= filteredOpportunities.length">
                    <el-icon><ArrowRight /></el-icon>
                  </el-button>
                </el-button-group>
                <span style="font-size: 12px; color: #666; margin-right: 10px;">
                  第 {{ currentOpportunityPage + 1 }} 页，共 {{ totalOpportunityPages }} 页
                </span>
                <el-switch
                  v-model="opportunityAutoSwitch"
                  active-text="自动轮播"
                  size="small"
                  style="margin-right: 10px;"
                  @change="toggleOpportunityAutoSwitch"
                />
                <el-button type="primary" size="small" @click="openConfigDialog">
                  ⚙️ 配置策略
                </el-button>
              </div>
            </div>
          </template>

          <div class="opportunities-list">
            <div 
              v-for="opp in getCurrentPageOpportunities()" 
              :key="opp.id"
              :class="[
                'opportunity-item', 
                opp.riskLevel,
                opp.status,
                getStrategyClass(opp.strategy)
              ]"
            >
              <div class="opp-header">
                <div class="opp-title">
                  <strong>{{ opp.symbol }}</strong>
                  <el-tag :type="getRiskTagType(opp.riskLevel)" size="small">
                    {{ getRiskText(opp.riskLevel) }}
                  </el-tag>
                  <el-tag :type="getStrategyTagType(opp.strategy)" size="small">
                    {{ getStrategyName(opp.strategy) }}
                  </el-tag>
                </div>
                <div class="opp-duration">
                  <el-tag size="small" :type="opp.status === 'active' ? 'success' : 'info'">
                    {{ opp.status === 'active' ? '活跃' : '已失效' }}
                  </el-tag>
                  <span>{{ Math.floor(opp.duration / 60) }}:{{ String(opp.duration % 60).padStart(2, '0') }}</span>
                </div>
              </div>

              <div class="opp-exchanges">
                <div class="exchange-pair">
                  <span class="high-exchange">
                    {{ opp.highExchange }} ({{ getExchangeType(opp.highExchange) }})
                    <div class="price">卖一: ${{ opp.highAsk.toFixed(2) }}</div>
                    <div class="action short">开空单</div>
                  </span>
                  <span class="arrow">⚡</span>
                  <span class="low-exchange">
                    {{ opp.lowExchange }} ({{ getExchangeType(opp.lowExchange) }})
                    <div class="price">买一: ${{ opp.lowBid.toFixed(2) }}</div>
                    <div class="action long">开多单</div>
                  </span>
                </div>
              </div>

              <div class="opp-metrics">
                <div class="metric-row">
                  <div class="metric">
                    <span class="label">显示价差</span>
                    <span class="value">${{ opp.priceDiff.toFixed(2) }} ({{ opp.diffPercent.toFixed(3) }}%)</span>
                  </div>
                  <div class="metric important">
                    <span class="label">真实价差</span>
                    <span class="value">${{ opp.realSpread.toFixed(2) }} ({{ opp.realSpreadPercent.toFixed(3) }}%)</span>
                  </div>
                  <div class="metric">
                    <span class="label">预计执行</span>
                    <span class="value">{{ opp.executionTime }}秒</span>
                  </div>
                </div>

                <div class="cost-breakdown">
                  <div class="cost-item">
                    <span>预期滑点: -${{ opp.expectedSlippage.toFixed(2) }}</span>
                  </div>
                  <div class="cost-item">
                    <span>手续费: -${{ opp.totalFees.toFixed(2) }}</span>
                  </div>
                  <div v-if="opp.gasEstimate" class="cost-item">
                    <span>Gas费用: -${{ opp.gasEstimate.toFixed(2) }}</span>
                  </div>
                  <div v-if="opp.impermanentLossRisk" class="cost-item">
                    <span>无常损失风险: -${{ opp.impermanentLossRisk.toFixed(2) }}</span>
                  </div>
                </div>

                <div class="profit-analysis">
                  <div class="profit-item" :class="{ negative: opp.netProfitPotential < 0 }">
                    <span class="label">净利润潜力:</span>
                    <span class="value">
                      {{ opp.netProfitPotential > 0 ? '+' : '' }}${{ opp.netProfitPotential.toFixed(2) }}
                      <small v-if="opp.netProfitPotential < 0">（不建议执行）</small>
                    </span>
                  </div>
                  <div class="execution-time">
                    预计执行时间: {{ opp.executionTime }}秒
                  </div>
                </div>

                <div class="tags-section">
                  <div class="risks">
                    <strong>主要风险:</strong>
                    <el-tag 
                      v-for="risk in opp.risks.slice(0, 3)" 
                      :key="risk"
                      size="small" 
                      type="danger" 
                      effect="plain"
                    >
                      {{ risk }}
                    </el-tag>
                  </div>
                  <div class="advantages">
                    <strong>主要优势:</strong>
                    <el-tag 
                      v-for="advantage in opp.advantages.slice(0, 3)" 
                      :key="advantage"
                      size="small" 
                      type="success" 
                      effect="plain"
                    >
                      {{ advantage }}
                    </el-tag>
                  </div>
                </div>
              </div>

              <div class="opp-actions">
                <el-button 
                  v-if="opp.netProfitPotential > 0"
                  type="primary" 
                  size="small"
                  @click="executeArbitrage(opp)"
                  :disabled="opp.status !== 'active'"
                >
                  手动执行
                </el-button>
                <el-button 
                  v-else
                  size="small" 
                  type="info" 
                  disabled
                >
                  不推荐执行
                </el-button>
                <el-button size="small" @click="showDetails(opp)">详情</el-button>
              </div>
            </div>

            <div v-if="filteredOpportunities.length === 0" class="no-opportunities">
              <el-empty description="暂无符合条件的套利机会">
                <el-button type="primary" @click="updateData">刷新数据</el-button>
              </el-empty>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 第三行：历史套利机会 - 单独占满一行 -->
    <el-row style="margin-top: 20px;">
      <el-col :span="24">
        <el-card class="history-opportunities-card">
          <template #header>
            <div class="history-header">
              <h3>📊 历史套利机会分析</h3>
              <div class="header-controls">
                <el-select v-model="historyTimeFilter" size="small" style="width: 120px; margin-right: 10px;">
                  <el-option label="1小时" value="1h" />
                  <el-option label="24小时" value="24h" />
                  <el-option label="7天" value="7d" />
                  <el-option label="30天" value="30d" />
                </el-select>
                <el-select v-model="historyStatusFilter" size="small" style="width: 120px; margin-right: 10px;">
                  <el-option label="全部" value="all" />
                  <el-option label="已错过" value="missed" />
                  <el-option label="已执行" value="executed" />
                  <el-option label="进行中" value="active" />
                </el-select>
                <el-button size="small" @click="refreshHistoryOpportunities">刷新</el-button>
              </div>
            </div>
          </template>
          
          <div class="history-opportunities-list">
            <div v-for="hist in getFilteredHistoryOpportunities()" :key="hist.id" class="history-opportunity-item">
              <div class="hist-header">
                <span class="symbol">{{ hist.symbol }}</span>
                <el-tag :type="getStatusTagType(hist.status)" size="small">
                  {{ getStatusText(hist.status) }}
                </el-tag>
                <el-tag :type="getStrategyTagType(hist.strategy)" size="small">
                  {{ getStrategyName(hist.strategy) }}
                </el-tag>
                <span class="duration">持续: {{ hist.durationSeconds }}s</span>
              </div>
              
              <div class="hist-details">
                <div class="profit-comparison">
                  <div class="potential-profit">
                    预期收益: <span class="profit">
                      {{ hist.theoreticalProfit > 0 ? '+' : '' }}${{ hist.theoreticalProfit.toFixed(2) }}
                    </span>
                  </div>
                  <div v-if="hist.actualProfit !== undefined" class="actual-profit">
                    实际收益: <span :class="{ profit: hist.actualProfit > 0, loss: hist.actualProfit < 0 }">
                      {{ hist.actualProfit > 0 ? '+' : '' }}${{ hist.actualProfit.toFixed(2) }}
                    </span>
                  </div>
                </div>
                
                <div class="price-info">
                  <span>{{ hist.highExchange }}: ${{ hist.highPrice.toFixed(2) }}</span>
                  <span class="arrow">→</span>
                  <span>{{ hist.lowExchange }}: ${{ hist.lowPrice.toFixed(2) }}</span>
                  <span class="spread">差价: ${{ hist.priceDiff.toFixed(2) }}</span>
                </div>
                
                <div class="hist-time">
                  {{ formatTime(hist.detectionTime) }}
                  <span v-if="hist.missedReason" class="missed-reason">
                    ({{ hist.missedReason }})
                  </span>
                  <span v-if="hist.expiredReason" class="expired-reason">
                    ({{ hist.expiredReason }})
                  </span>
                </div>
                
                <!-- 添加更多详细信息 -->
                <div class="additional-info">
                  <div class="real-spread">
                    真实价差: <span :class="{ profit: hist.realSpread > 0, loss: hist.realSpread < 0 }">
                      {{ hist.realSpread > 0 ? '+' : '' }}${{ hist.realSpread.toFixed(2) }}
                      ({{ hist.realSpreadPercent.toFixed(3) }}%)
                    </span>
                  </div>
                  <div v-if="hist.executionTime" class="execution-time">
                    执行时间: {{ hist.executionTime }}s
                  </div>
                  <div v-if="hist.slippageLoss" class="slippage-loss">
                    滑点损失: ${{ hist.slippageLoss.toFixed(2) }}
                  </div>
                  <div v-if="hist.totalFees" class="total-fees">
                    手续费: ${{ hist.totalFees.toFixed(2) }}
                  </div>
                </div>
                
                <!-- 风险因素 -->
                <div v-if="hist.riskFactors && hist.riskFactors.length > 0" class="risk-factors">
                  <span class="label">风险因素:</span>
                  <el-tag 
                    v-for="risk in hist.riskFactors" 
                    :key="risk"
                    size="small" 
                    type="warning" 
                    effect="plain"
                    style="margin-right: 4px; margin-top: 4px;"
                  >
                    {{ risk }}
                  </el-tag>
                </div>
              </div>
            </div>
            
            <div v-if="getFilteredHistoryOpportunities().length === 0" class="no-history-opportunities">
              <el-empty description="暂无历史套利机会记录">
                <el-button type="primary" @click="refreshHistoryOpportunities">刷新数据</el-button>
              </el-empty>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 套利配置弹窗 -->
    <el-dialog
      v-model="configDialogVisible"
      title="套利策略配置"
      width="80%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      top="5vh"
    >
      <div class="config-dialog-content">
        <el-tabs v-model="activeConfigTab" type="border-card">
          <el-tab-pane 
            v-for="config in getStrategyConfigs()" 
            :key="config.symbol" 
            :label="config.symbol" 
            :name="config.symbol"
          >
            <div class="config-item">
              <div class="config-header-item">
                <div class="symbol-info">
                  <span class="symbol">{{ config.symbol }}</span>
                  <el-tag :type="getRiskTagType(config.riskLevel)" size="small">
                    {{ getRiskText(config.riskLevel) }}
                  </el-tag>
                  <el-tag :type="getStrategyTagType(selectedStrategy)" size="small">
                    {{ getStrategyName(selectedStrategy) }}
                  </el-tag>
                </div>
                <el-switch v-model="config.enabled" />
              </div>
              
              <!-- 基础配置 -->
              <div class="config-sections">
                <div class="config-section">
                  <h4>💰 基础参数</h4>
                  <div class="config-grid">
                    <div class="config-item-detail">
                      <label>最小利润 (USD)</label>
                      <el-input-number 
                        v-model="config.minProfitUSD" 
                        :min="5" 
                        :max="1000" 
                        :step="5"
                        size="small"
                        :disabled="!config.enabled"
                      />
                    </div>
                    <div class="config-item-detail">
                      <label>最大仓位 (USD)</label>
                      <el-input-number 
                        v-model="config.maxPositionUSD" 
                        :min="1000" 
                        :max="1000000" 
                        :step="1000"
                        size="small"
                        :disabled="!config.enabled"
                      />
                    </div>
                    <div class="config-item-detail">
                      <label>最大持仓 (分钟)</label>
                      <el-input-number 
                        v-model="config.maxHoldingMinutes" 
                        :min="5" 
                        :max="480" 
                        :step="5"
                        size="small"
                        :disabled="!config.enabled"
                      />
                    </div>
                    <div class="config-item-detail">
                      <label>自动执行</label>
                      <el-switch v-model="config.autoExecute" :disabled="!config.enabled" />
                    </div>
                  </div>
                </div>
                
                <!-- CEX-CEX 特定配置 -->
                <div v-if="config.strategy === 'CEX_CEX'" class="config-section">
                  <h4>🏦 CEX 配置</h4>
                  <div class="config-grid">
                    <div class="config-item-detail">
                      <label>最大滑点 (%)</label>
                      <el-input-number 
                        v-model="config.slippage.maxSlippagePercent" 
                        :min="0.01" 
                        :max="0.5" 
                        :step="0.01"
                        :precision="3"
                        size="small"
                        :disabled="!config.enabled"
                      />
                    </div>
                    <div class="config-item-detail">
                      <label>执行速度 (毫秒)</label>
                      <el-input-number 
                        v-model="config.slippage.executionSpeedMs" 
                        :min="1000" 
                        :max="10000" 
                        :step="1000"
                        size="small"
                        :disabled="!config.enabled"
                      />
                    </div>
                    <div class="config-item-detail">
                      <label>最大杠杆</label>
                      <el-input-number 
                        v-model="config.leverage.maxLeverage" 
                        :min="1" 
                        :max="10" 
                        :step="1"
                        size="small"
                        :disabled="!config.enabled || !config.leverage.enabled"
                      />
                    </div>
                    <div class="config-item-detail">
                      <label>杠杆交易</label>
                      <el-switch v-model="config.leverage.enabled" :disabled="!config.enabled" />
                    </div>
                  </div>
                  
                  <div class="exchanges-config">
                    <label>主要交易所</label>
                    <div class="exchanges-list">
                      <el-tag 
                        v-for="exchange in config.exchanges.primary" 
                        :key="exchange"
                        size="small"
                        closable
                        @close="removeExchange(config, 'primary', exchange)"
                      >
                        {{ exchange }}
                      </el-tag>
                    </div>
                  </div>
                </div>
                
                <!-- DEX-DEX 特定配置 -->
                <div v-else-if="config.strategy === 'DEX_DEX'" class="config-section">
                  <h4>🔗 DEX 配置</h4>
                  <div class="config-grid">
                    <div class="config-item-detail">
                      <label>最大滑点 (%)</label>
                      <el-input-number 
                        v-model="config.slippage.maxSlippagePercent" 
                        :min="0.1" 
                        :max="5.0" 
                        :step="0.1"
                        :precision="2"
                        size="small"
                        :disabled="!config.enabled"
                      />
                    </div>
                    <div class="config-item-detail">
                      <label>最大Gas (USD)</label>
                      <el-input-number 
                        v-model="config.gas.maxGasLimitUSD" 
                        :min="10" 
                        :max="200" 
                        :step="5"
                        size="small"
                        :disabled="!config.enabled"
                      />
                    </div>
                    <div class="config-item-detail">
                      <label>最大Gas价格 (Gwei)</label>
                      <el-input-number 
                        v-model="config.gas.maxGasPriceGwei" 
                        :min="5" 
                        :max="200" 
                        :step="5"
                        size="small"
                        :disabled="!config.enabled"
                      />
                    </div>
                    <div class="config-item-detail">
                      <label>无常损失监控</label>
                      <el-switch v-model="config.slippage.impermanentLoss.monitoringEnabled" :disabled="!config.enabled" />
                    </div>
                  </div>
                  
                  <div class="config-grid">
                    <div class="config-item-detail">
                      <label>最大无常损失 (%)</label>
                      <el-input-number 
                        v-model="config.slippage.impermanentLoss.maxRiskPercent" 
                        :min="0.1" 
                        :max="10.0" 
                        :step="0.1"
                        :precision="2"
                        size="small"
                        :disabled="!config.enabled"
                      />
                    </div>
                    <div class="config-item-detail">
                      <label>最小流动性 (USD)</label>
                      <el-input-number 
                        v-model="config.slippage.minLiquidityUSD" 
                        :min="10000" 
                        :max="10000000" 
                        :step="10000"
                        size="small"
                        :disabled="!config.enabled"
                      />
                    </div>
                    <div class="config-item-detail">
                      <label>Gas速度模式</label>
                      <el-select v-model="config.gas.speedMode" size="small" :disabled="!config.enabled">
                        <el-option label="慢速" value="slow" />
                        <el-option label="标准" value="standard" />
                        <el-option label="快速" value="fast" />
                        <el-option label="极速" value="instant" />
                      </el-select>
                    </div>
                    <div class="config-item-detail">
                      <label>跨链桥接</label>
                      <el-switch v-model="config.bridging.enabled" :disabled="!config.enabled" />
                    </div>
                  </div>
                  
                  <div class="networks-config">
                    <label>主要网络</label>
                    <div class="networks-list">
                      <el-tag 
                        v-for="network in config.networks.primary" 
                        :key="network"
                        size="small"
                        :type="getNetworkTagType(network)"
                      >
                        {{ network }}
                      </el-tag>
                    </div>
                  </div>
                </div>
                
                <!-- CEX-DEX 混合配置 -->
                <div v-else-if="config.strategy === 'CEX_DEX'" class="config-section">
                  <h4>🔄 混合策略配置</h4>
                  <div class="config-grid">
                    <div class="config-item-detail">
                      <label>最大组合滑点 (%)</label>
                      <el-input-number 
                        v-model="config.complexRisks.maxCombinedSlippage" 
                        :min="0.1" 
                        :max="3.0" 
                        :step="0.1"
                        :precision="2"
                        size="small"
                        :disabled="!config.enabled"
                      />
                    </div>
                    <div class="config-item-detail">
                      <label>最大Gas影响 (%)</label>
                      <el-input-number 
                        v-model="config.complexRisks.maxGasImpactPercent" 
                        :min="0.1" 
                        :max="2.0" 
                        :step="0.1"
                        :precision="2"
                        size="small"
                        :disabled="!config.enabled"
                      />
                    </div>
                    <div class="config-item-detail">
                      <label>CEX优先执行</label>
                      <el-switch v-model="config.executionPriority.cexFirst" :disabled="!config.enabled" />
                    </div>
                    <div class="config-item-detail">
                      <label>资金自动桥接</label>
                      <el-switch v-model="config.fundBridging.autobridge" :disabled="!config.enabled" />
                    </div>
                  </div>
                  
                  <div class="hybrid-exchanges">
                    <div class="exchange-group">
                      <label>CEX交易所</label>
                      <div class="exchanges-list">
                        <el-tag 
                          v-for="exchange in config.cexExchanges" 
                          :key="exchange"
                          size="small"
                          type="success"
                        >
                          {{ exchange }}
                        </el-tag>
                      </div>
                    </div>
                  </div>
                </div>
                
                <!-- 风险控制配置 -->
                <div class="config-section">
                  <h4>⚡ 风险控制</h4>
                  <div class="config-grid">
                    <div class="config-item-detail">
                      <label>止损 (%)</label>
                      <el-input-number 
                        v-model="config.stopLossPercent" 
                        :min="0.1" 
                        :max="10.0" 
                        :step="0.1"
                        :precision="2"
                        size="small"
                        :disabled="!config.enabled"
                      />
                    </div>
                    <div class="config-item-detail">
                      <label>止盈 (%)</label>
                      <el-input-number 
                        v-model="config.takeProfitPercent" 
                        :min="0.1" 
                        :max="20.0" 
                        :step="0.1"
                        :precision="2"
                        size="small"
                        :disabled="!config.enabled"
                      />
                    </div>
                    <div class="config-item-detail">
                      <label>风险等级</label>
                      <el-select v-model="config.riskLevel" size="small" :disabled="!config.enabled">
                        <el-option label="保守" value="conservative" />
                        <el-option label="适中" value="moderate" />
                        <el-option label="激进" value="aggressive" />
                      </el-select>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="configDialogVisible = false">取消</el-button>
          <el-button @click="resetConfigs" type="warning">重置默认</el-button>
          <el-button @click="exportConfigs" type="info">导出配置</el-button>
          <el-button @click="importConfigs" type="success">导入配置</el-button>
          <el-button @click="saveAndCloseConfig" type="primary">保存配置</el-button>
        </div>
      </template>
    </el-dialog>



    <!-- 第四行：操作记录 - 单独占满一行 -->
    <el-row style="margin-top: 20px;">
      <el-col :span="24">
        <el-card class="operations-card">
          <template #header>
            <div class="operations-header">
              <h3>📋 操作记录</h3>
              <div class="header-controls">
                <el-button size="small" @click="clearOperations">清空记录</el-button>
                <el-button size="small" type="primary" @click="exportOperations">导出记录</el-button>
              </div>
            </div>
          </template>
          
          <div class="operations-list">
            <div v-for="op in getFilteredOperations()" :key="op.id" class="operation-item">
              <div class="op-header">
                <span class="symbol">{{ op.symbol }}</span>
                <el-tag :type="getOperationStatusType(op.status)" size="small">
                  {{ getOperationStatusText(op.status) }}
                </el-tag>
                <el-tag :type="getStrategyTagType(op.strategy)" size="small">
                  {{ getStrategyName(op.strategy) }}
                </el-tag>
              </div>
              <div class="op-details">
                <div class="positions">
                  <div v-for="pos in op.positions" :key="pos.exchange" class="position">
                    {{ pos.exchange }}({{ pos.exchangeType }}) 
                    <span :class="pos.side">{{ pos.side === 'long' ? '多' : '空' }}</span>: 
                    ${{ pos.entryPrice.toFixed(2) }}
                    <span v-if="pos.pnl !== undefined" :class="{ profit: pos.pnl > 0, loss: pos.pnl < 0 }">
                      {{ pos.pnl > 0 ? '+' : '' }}${{ pos.pnl.toFixed(2) }}
                    </span>
                  </div>
                </div>
                <div class="op-summary">
                  <span v-if="op.netProfit !== undefined" :class="{ profit: op.netProfit > 0, loss: op.netProfit < 0 }">
                    净收益: {{ op.netProfit > 0 ? '+' : '' }}${{ op.netProfit.toFixed(2) }}
                  </span>
                  <span>手续费: ${{ op.totalFees.toFixed(2) }}</span>
                  <span v-if="op.totalGasCost">Gas: ${{ op.totalGasCost.toFixed(2) }}</span>
                  <span v-if="op.totalImpermanentLoss">IL: ${{ op.totalImpermanentLoss.toFixed(2) }}</span>
                </div>
                <div class="op-time">
                  {{ formatTime(op.startTime) }}
                  <span v-if="op.executionTimeActual"> ({{ op.executionTimeActual }}s)</span>
                </div>
              </div>
            </div>
            
            <div v-if="getFilteredOperations().length === 0" class="no-operations">
              <el-empty description="暂无操作记录" />
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue';
import { 
  mockPriceMonitor, 
  mockArbitrageOpportunities, 
  mockArbitrageConfigs, 
  mockArbitrageOperations,
  exchangeDatabase,
  updatePriceMonitor,
  updateArbitrageOpportunities,
  getStrategyAnalysis,
  ArbitrageStrategy,
  ExchangeType,
  type PriceMonitorData,
  type ArbitrageOpportunity,
  type ArbitrageConfig,
  type ArbitrageOperation,
  type ExchangeInfo
} from '@/mock/arbitrageData';
import { ElMessage, ElMessageBox } from 'element-plus';
import { ArrowLeft, ArrowRight } from '@element-plus/icons-vue';

// 响应式数据
const selectedStrategy = ref<ArbitrageStrategy>(ArbitrageStrategy.CEX_CEX);
const priceMonitorData = ref<PriceMonitorData[]>(mockPriceMonitor);
const opportunitiesData = ref<ArbitrageOpportunity[]>(mockArbitrageOpportunities);
const configData = ref<ArbitrageConfig[]>(mockArbitrageConfigs);
const operationsData = ref<ArbitrageOperation[]>(mockArbitrageOperations);
const autoUpdate = ref(true);
const updating = ref(false);
let updateTimer: number | null = null;
const configDialogVisible = ref(false);
const activeConfigTab = ref('BTC/USDT');

// 轮播和分页相关
const selectedSymbol = ref('BTC/USDT') // 默认选择 BTC/USDT
const symbolAutoSwitch = ref(false)
const symbolSwitchInterval = ref<number | null>(null)
const currentOpportunityPage = ref(0)
const opportunitiesPerPage = ref(3)
const opportunityAutoSwitch = ref(false)
const opportunitySwitchInterval = ref<number | null>(null)

// 历史套利机会相关
const historyOpportunities = ref<any[]>([])
const historyTimeFilter = ref('24h')
const historyStatusFilter = ref('all')

// 计算属性
const currentAnalysis = computed(() => getStrategyAnalysis(selectedStrategy.value));

const filteredOpportunities = computed(() => {
  return opportunitiesData.value.filter(opp => opp.strategy === selectedStrategy.value);
});

const availableSymbols = computed(() => {
  return priceMonitorData.value.map(item => item.symbol)
});

const totalOpportunityPages = computed(() => {
  return Math.ceil(filteredOpportunities.value.length / opportunitiesPerPage.value)
});

// 方法
const onStrategyChange = (strategy: ArbitrageStrategy) => {
  selectedStrategy.value = strategy;
  ElMessage.info(`已切换到${getStrategyAnalysis(strategy).name}策略`);
};

const getFilteredExchanges = (): ExchangeInfo[] => {
  if (selectedStrategy.value === ArbitrageStrategy.CEX_CEX) {
    return exchangeDatabase.filter(ex => ex.type === ExchangeType.CEX);
  } else if (selectedStrategy.value === ArbitrageStrategy.DEX_DEX) {
    return exchangeDatabase.filter(ex => ex.type === ExchangeType.DEX);
  } else {
    return exchangeDatabase; // CEX_DEX 显示所有
  }
};

const getExchangeType = (exchangeName: string): string => {
  const exchange = exchangeDatabase.find(ex => ex.name === exchangeName);
  return exchange?.type || 'CEX';
};

const getStrategyName = (strategy: ArbitrageStrategy): string => {
  const names = {
    [ArbitrageStrategy.CEX_CEX]: 'CEX-CEX',
    [ArbitrageStrategy.DEX_DEX]: 'DEX-DEX',
    [ArbitrageStrategy.CEX_DEX]: 'CEX-DEX'
  };
  return names[strategy];
};

const getStrategyClass = (strategy: ArbitrageStrategy): string => {
  return strategy.toLowerCase().replace('_', '-');
};

const getStrategyTagType = (strategy: ArbitrageStrategy): string => {
  const types = {
    [ArbitrageStrategy.CEX_CEX]: 'success',
    [ArbitrageStrategy.DEX_DEX]: 'warning',
    [ArbitrageStrategy.CEX_DEX]: 'danger'
  };
  return types[strategy];
};

const getRiskTagType = (risk: string): string => {
  const types = { low: 'success', medium: 'warning', high: 'danger' };
  return types[risk as keyof typeof types] || 'info';
};

const getProfitTagType = (profit: string): string => {
  const types = { low: 'info', medium: 'warning', high: 'success' };
  return types[profit as keyof typeof types] || 'info';
};

const getRiskLevelText = (risk: string): string => {
  const texts = { low: '低风险', medium: '中风险', high: '高风险' };
  return texts[risk as keyof typeof texts] || risk;
};

const getProfitPotentialText = (profit: string): string => {
  const texts = { low: '低收益', medium: '中收益', high: '高收益' };
  return texts[profit as keyof typeof texts] || profit;
};

const getComplexityRate = (complexity: string): number => {
  const rates = { low: 2, medium: 3, high: 5 };
  return rates[complexity as keyof typeof rates] || 3;
};

const getCharacteristicText = (level: string): string => {
  const texts = { high: '高', medium: '中', low: '低' };
  return texts[level as keyof typeof texts] || level;
};

const getCharacteristicTagType = (level: string): string => {
  const types = { 
    high: 'success', 
    medium: 'warning', 
    low: 'danger' 
  };
  return types[level as keyof typeof types] || 'info';
};

const getOperationStatusType = (status: string): string => {
  const types = {
    'pending': 'info',
    'active': 'warning', 
    'completed': 'success',
    'failed': 'danger'
  };
  return types[status as keyof typeof types] || 'info';
};

const getOperationStatusText = (status: string): string => {
  const texts = {
    'pending': '待处理',
    'active': '进行中',
    'completed': '已完成', 
    'failed': '失败'
  };
  return texts[status as keyof typeof texts] || status;
};

const formatNumber = (num: number): string => {
  return new Intl.NumberFormat('zh-CN', {
    notation: 'compact',
    maximumFractionDigits: 1
  }).format(num);
};

const updateData = () => {
  updating.value = true;
  setTimeout(() => {
    updatePriceMonitor();
    updateArbitrageOpportunities();
    priceMonitorData.value = [...mockPriceMonitor];
    opportunitiesData.value = [...mockArbitrageOpportunities];
    updating.value = false;
  }, 500);
};

const toggleAutoUpdate = (enabled: boolean) => {
  if (enabled) {
    startAutoUpdate();
  } else {
    stopAutoUpdate();
  }
};

const startAutoUpdate = () => {
  if (updateTimer) return;
  updateTimer = window.setInterval(() => {
    updateData();
  }, 2000);
};

const stopAutoUpdate = () => {
  if (updateTimer) {
    clearInterval(updateTimer);
    updateTimer = null;
  }
};

const executeArbitrage = (opportunity: ArbitrageOpportunity) => {
  ElMessageBox.confirm(
    `确定要执行 ${opportunity.symbol} 的套利操作吗？\n预计净收益: $${opportunity.netProfitPotential.toFixed(2)}`,
    '确认执行套利',
    {
      confirmButtonText: '执行',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    ElMessage.success(`正在执行 ${opportunity.symbol} 套利操作...`);
    // 这里应该调用实际的套利执行API
  }).catch(() => {
    ElMessage.info('已取消套利操作');
  });
};

const showDetails = (opportunity: ArbitrageOpportunity) => {
  // 显示详细信息的弹窗或跳转到详情页
  ElMessage.info('显示详细信息功能待实现');
  console.log('Opportunity details:', opportunity); // 暂时用console.log避免linter错误
};

// 生命周期
onMounted(() => {
  // 首先更新数据
  updateData();
  
  // 确保选中的交易对在可用列表中，如果不在则选择第一个
  if (availableSymbols.value.length > 0) {
    if (!availableSymbols.value.includes(selectedSymbol.value)) {
      selectedSymbol.value = availableSymbols.value[0];
      console.log('selectedSymbol corrected to:', selectedSymbol.value);
    }
    console.log('Available symbols:', availableSymbols.value);
    console.log('Current selected symbol:', selectedSymbol.value);
  }
  
  loadMockHistoryOpportunities(); // 加载历史数据
  if (autoUpdate.value) {
    startAutoUpdate();
  }
});

onUnmounted(() => {
  stopAutoUpdate();
  // 清理轮播定时器
  if (symbolSwitchInterval.value) {
    clearInterval(symbolSwitchInterval.value)
    symbolSwitchInterval.value = null
  }
  if (opportunitySwitchInterval.value) {
    clearInterval(opportunitySwitchInterval.value)
    opportunitySwitchInterval.value = null
  }
});

// 新增方法
const getStrategyConfigs = () => {
  return configData.value.filter(config => 
    selectedStrategy.value === ArbitrageStrategy.CEX_CEX ? config.strategy === 'CEX_CEX' :
    selectedStrategy.value === ArbitrageStrategy.DEX_DEX ? config.strategy === 'DEX_DEX' :
    selectedStrategy.value === ArbitrageStrategy.CEX_DEX ? config.strategy === 'CEX_DEX' :
    true
  );
};

const getRiskText = (riskLevel: string): string => {
  const texts = { 
    conservative: '保守', 
    moderate: '适中', 
    aggressive: '激进',
    low: '低',
    medium: '中',
    high: '高'
  };
  return texts[riskLevel as keyof typeof texts] || riskLevel;
};

const getNetworkTagType = (network: string): string => {
  const types: { [key: string]: string } = {
    'Ethereum': 'primary',
    'Arbitrum': 'success', 
    'Polygon': 'warning',
    'BSC': 'danger',
    'Optimism': 'info',
    'Solana': 'warning'
  };
  return types[network] || 'info';
};

const removeExchange = (config: any, type: string, exchange: string) => {
  if (type === 'primary' && config.exchanges?.primary) {
    const index = config.exchanges.primary.indexOf(exchange);
    if (index > -1) {
      config.exchanges.primary.splice(index, 1);
    }
  }
  ElMessage.success(`已移除交易所: ${exchange}`);
};

const getFilteredOperations = () => {
  return operationsData.value.filter(op => 
    selectedStrategy.value === ArbitrageStrategy.CEX_CEX ? op.strategy === ArbitrageStrategy.CEX_CEX :
    selectedStrategy.value === ArbitrageStrategy.DEX_DEX ? op.strategy === ArbitrageStrategy.DEX_DEX :
    selectedStrategy.value === ArbitrageStrategy.CEX_DEX ? op.strategy === ArbitrageStrategy.CEX_DEX :
    true
  ).slice(0, 8); // 只显示最近8条记录
};

const formatTime = (timestamp: number): string => {
  return new Date(timestamp).toLocaleString('zh-CN');
};

// 配置管理方法
const saveConfigs = () => {
  // 这里可以实现保存到localStorage或发送到后端
  localStorage.setItem('arbitrageConfigs', JSON.stringify(configData.value));
  ElMessage.success('配置已保存');
};

const resetConfigs = () => {
  ElMessageBox.confirm('确定要重置所有配置为默认值吗？', '确认重置', {
    confirmButtonText: '重置',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    // 这里重置配置为默认值
    ElMessage.success('配置已重置为默认值');
  }).catch(() => {
    ElMessage.info('已取消重置操作');
  });
};

const exportConfigs = () => {
  const configs = getStrategyConfigs();
  const dataStr = JSON.stringify(configs, null, 2);
  const dataBlob = new Blob([dataStr], { type: 'application/json' });
  const url = URL.createObjectURL(dataBlob);
  const link = document.createElement('a');
  link.href = url;
  link.download = `arbitrage-config-${new Date().toISOString().split('T')[0]}.json`;
  link.click();
  URL.revokeObjectURL(url);
  ElMessage.success('配置已导出');
};

const importConfigs = () => {
  // 创建一个隐藏的file input来选择文件
  const input = document.createElement('input');
  input.type = 'file';
  input.accept = '.json';
  input.onchange = (e) => {
    const file = (e.target as HTMLInputElement).files?.[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = (e) => {
        try {
          const importedConfigs = JSON.parse(e.target?.result as string);
          // 这里应该验证和应用配置
          console.log('Imported configs:', importedConfigs); // 暂时用console.log避免linter错误
          ElMessage.success('配置导入成功');
        } catch (error) {
          ElMessage.error('配置文件格式错误');
        }
      };
      reader.readAsText(file);
    }
  };
  input.click();
};

const clearOperations = () => {
  ElMessageBox.confirm('确定要清空所有操作记录吗？', '确认删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    // 这里应该调用API清空记录
    ElMessage.success('操作记录已清空');
  }).catch(() => {
    ElMessage.info('已取消清空操作');
  });
};

const openConfigDialog = () => {
  // 设置默认的Tab为当前策略的第一个配置
  const configs = getStrategyConfigs();
  if (configs.length > 0) {
    activeConfigTab.value = configs[0].symbol;
  }
  configDialogVisible.value = true;
};

const saveAndCloseConfig = () => {
  saveConfigs();
  configDialogVisible.value = false;
};

const exportOperations = () => {
  const dataStr = JSON.stringify(getFilteredOperations(), null, 2);
  const dataBlob = new Blob([dataStr], { type: 'application/json' });
  const url = URL.createObjectURL(dataBlob);
  const link = document.createElement('a');
  link.href = url;
  link.download = `arbitrage-operations-${new Date().toISOString().split('T')[0]}.json`;
  link.click();
  URL.revokeObjectURL(url);
  ElMessage.success('操作记录已导出');
};

// 交易对切换相关方法
const selectSymbol = (symbol: string) => {
  selectedSymbol.value = symbol
}

const onSymbolChange = () => {
  // 交易对变化时的处理
  updateData()
}

const prevSymbol = () => {
  const currentIndex = availableSymbols.value.indexOf(selectedSymbol.value)
  if (currentIndex > 0) {
    selectedSymbol.value = availableSymbols.value[currentIndex - 1]
  }
}

const nextSymbol = () => {
  const currentIndex = availableSymbols.value.indexOf(selectedSymbol.value)
  if (currentIndex < availableSymbols.value.length - 1) {
    selectedSymbol.value = availableSymbols.value[currentIndex + 1]
  } else {
    selectedSymbol.value = availableSymbols.value[0] // 循环到第一个
  }
}

const toggleSymbolAutoSwitch = (enabled: boolean) => {
  if (enabled && availableSymbols.value.length > 1) {
    symbolSwitchInterval.value = setInterval(() => {
      nextSymbol()
    }, 5000) // 每5秒切换
  } else if (symbolSwitchInterval.value) {
    clearInterval(symbolSwitchInterval.value)
    symbolSwitchInterval.value = null
  }
}

// 套利机会分页相关方法
const getCurrentPageOpportunities = () => {
  const start = currentOpportunityPage.value * opportunitiesPerPage.value
  const end = start + opportunitiesPerPage.value
  return filteredOpportunities.value.slice(start, end)
}

const prevOpportunityPage = () => {
  if (currentOpportunityPage.value > 0) {
    currentOpportunityPage.value--
  }
}

const nextOpportunityPage = () => {
  if ((currentOpportunityPage.value + 1) * opportunitiesPerPage.value < filteredOpportunities.value.length) {
    currentOpportunityPage.value++
  } else {
    currentOpportunityPage.value = 0 // 循环到第一页
  }
}

const toggleOpportunityAutoSwitch = (enabled: boolean) => {
  if (enabled && totalOpportunityPages.value > 1) {
    opportunitySwitchInterval.value = setInterval(() => {
      nextOpportunityPage()
    }, 8000) // 每8秒切换
  } else if (opportunitySwitchInterval.value) {
    clearInterval(opportunitySwitchInterval.value)
    opportunitySwitchInterval.value = null
  }
}

// 方法
// 获取当前选中交易对的数据
const getCurrentSymbolData = () => {
  return priceMonitorData.value.find(item => item.symbol === selectedSymbol.value)
}

// 历史套利机会相关方法
const getFilteredHistoryOpportunities = () => {
  let filtered = historyOpportunities.value

  // 时间过滤
  if (historyTimeFilter.value !== 'all') {
    const now = Date.now()
    const timeMap = {
      '1h': 60 * 60 * 1000,
      '24h': 24 * 60 * 60 * 1000,
      '7d': 7 * 24 * 60 * 60 * 1000,
      '30d': 30 * 24 * 60 * 60 * 1000
    }
    const timeLimit = timeMap[historyTimeFilter.value as keyof typeof timeMap]
    if (timeLimit) {
      filtered = filtered.filter(opp => now - opp.detectionTime < timeLimit)
    }
  }

  // 状态过滤
  if (historyStatusFilter.value !== 'all') {
    filtered = filtered.filter(opp => opp.status === historyStatusFilter.value)
  }

  return filtered.slice(0, 20) // 限制显示数量
}

// 添加缺失的方法
const getStatusTagType = (status: string): string => {
  const types = {
    'executed': 'success',
    'missed': 'warning', 
    'expired': 'info',
    'active': 'primary'
  }
  return types[status as keyof typeof types] || 'info'
}

const getStatusText = (status: string): string => {
  const texts = {
    'executed': '已执行',
    'missed': '未执行',
    'expired': '已失效',
    'active': '进行中'
  }
  return texts[status as keyof typeof texts] || status
}

const refreshHistoryOpportunities = () => {
  // 模拟刷新历史数据
  ElMessage.success('历史数据已刷新')
  loadMockHistoryOpportunities()
}

// 加载模拟历史数据
const loadMockHistoryOpportunities = () => {
  const mockHistory = [
    {
      id: 'h001',
      symbol: 'BTC/USDT',
      strategy: ArbitrageStrategy.CEX_CEX,
      status: 'executed',
      detectionTime: Date.now() - 2 * 60 * 60 * 1000, // 2小时前
      durationSeconds: 180,
      highExchange: 'Binance',
      lowExchange: 'OKX',
      highPrice: 43520.50,
      lowPrice: 43485.20,
      priceDiff: 35.30,
      diffPercent: 0.081,
      realSpread: 28.45,
      realSpreadPercent: 0.065,
      theoreticalProfit: 125.80,
      actualProfit: 98.45,
      executionTime: 3.2,
      slippageLoss: 12.35,
      totalFees: 15.00,
      riskFactors: ['流动性风险', '执行延迟']
    },
    {
      id: 'h002',
      symbol: 'ETH/USDT',
      strategy: ArbitrageStrategy.DEX_DEX,
      status: 'missed',
      detectionTime: Date.now() - 4 * 60 * 60 * 1000, // 4小时前
      durationSeconds: 45,
      highExchange: 'Uniswap',
      lowExchange: 'SushiSwap',
      highPrice: 2650.80,
      lowPrice: 2635.20,
      priceDiff: 15.60,
      diffPercent: 0.059,
      realSpread: 8.90,
      realSpreadPercent: 0.034,
      theoreticalProfit: 85.50,
      missedReason: '资金不足',
      riskFactors: ['无常损失', 'Gas费波动', 'MEV攻击']
    },
    {
      id: 'h003',
      symbol: 'BNB/USDT',
      strategy: ArbitrageStrategy.CEX_DEX,
      status: 'expired',
      detectionTime: Date.now() - 6 * 60 * 60 * 1000, // 6小时前
      durationSeconds: 25,
      highExchange: 'Pancakeswap',
      lowExchange: 'Binance',
      highPrice: 315.80,
      lowPrice: 314.20,
      priceDiff: 1.60,
      diffPercent: 0.051,
      realSpread: -2.40,
      realSpreadPercent: -0.076,
      theoreticalProfit: -15.20,
      expiredReason: '价差消失',
      riskFactors: ['跨链风险', '流动性不足']
    }
  ]
  
  historyOpportunities.value = mockHistory
}
</script>

<style scoped>
.arbitrage-page {
  padding: 20px;
  min-height: 100vh;
  background: linear-gradient(135deg, #f1f5f9 0%, #e2e8f0 100%);
}

/* Element Plus Card 样式 */
.el-card {
  border: none;
  border-radius: 16px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
}

.el-card:hover {
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
  transform: translateY(-2px);
}

.el-card .el-card__header {
  background: linear-gradient(135deg, #ffffff 0%, #f8fafc 100%);
  border-bottom: 1px solid #e2e8f0;
  border-radius: 16px 16px 0 0;
}

.el-card .el-card__header h3 {
  margin: 0;
  color: #1e293b;
  font-size: 18px;
  font-weight: 600;
}

.el-card .el-card__body {
  padding: 24px;
}

/* 策略选择区域 */
.strategy-card .strategy-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.strategy-selector {
  margin: 16px 0;
}

.strategy-selector .el-radio-group {
  width: 100%;
  display: flex;
  flex-direction: row;
  gap: 8px;
  justify-content: space-between;
}

.strategy-selector .el-radio-button {
  flex: 1;
  margin-right: 0;
}

.strategy-selector .cex-cex .el-radio-button__inner {
  background: #f0f9ff;
  border-color: #0ea5e9;
  color: #0ea5e9;
}

.strategy-selector .cex-cex .el-radio-button__inner:hover {
  background: #e0f2fe;
}

.strategy-selector .dex-dex .el-radio-button__inner {
  background: #fef3c7;
  border-color: #f59e0b;
  color: #f59e0b;
}

.strategy-selector .dex-dex .el-radio-button__inner:hover {
  background: #fde68a;
}

.strategy-selector .cex-dex .el-radio-button__inner {
  background: #fee2e2;
  border-color: #ef4444;
  color: #ef4444;
}

.strategy-selector .cex-dex .el-radio-button__inner:hover {
  background: #fecaca;
}

/* 策略分析区域 */
.strategy-analysis .metrics-row {
  display: flex;
  gap: 16px;
  margin-bottom: 16px;
}

.strategy-analysis .metric {
  flex: 1;
}

.strategy-analysis .metric .label {
  font-size: 12px;
  color: #6b7280;
  display: block;
  margin-bottom: 4px;
}

.strategy-analysis .recommendation {
  margin: 16px 0;
  padding: 12px;
  background: #f3f4f6;
  border-radius: 6px;
  font-size: 14px;
}

.strategy-analysis .pros-cons {
  margin: 16px 0;
}

.strategy-analysis .pros h4,
.strategy-analysis .cons h4 {
  margin: 0 0 8px 0;
  font-size: 14px;
  font-weight: 600;
}

.strategy-analysis .pros h4 {
  color: #059669;
}

.strategy-analysis .cons h4 {
  color: #dc2626;
}

.strategy-analysis .pros ul,
.strategy-analysis .cons ul {
  margin: 0;
  padding-left: 16px;
  font-size: 12px;
}

.strategy-analysis .pros li {
  margin-bottom: 4px;
  line-height: 1.4;
  color: #047857;
}

.strategy-analysis .cons li {
  margin-bottom: 4px;
  line-height: 1.4;
  color: #b91c1c;
}

.strategy-analysis .best-practices {
  margin-top: 16px;
}

.strategy-analysis .best-practices h4 {
  margin: 0 0 8px 0;
  font-size: 14px;
  font-weight: 600;
  color: #7c3aed;
}

.strategy-analysis .best-practices ul {
  margin: 0;
  padding-left: 16px;
  font-size: 12px;
}

.strategy-analysis .best-practices li {
  margin-bottom: 4px;
  line-height: 1.4;
  color: #6366f1;
}

/* 交易所对比区域 */
.exchanges-card .exchanges-list {
  max-height: 400px;
  overflow-y: auto;
}

.exchanges-card .exchange-item {
  margin-bottom: 16px;
  padding: 12px;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
}

.exchanges-card .exchange-item.cex {
  background: #f0f9ff;
  border-color: #0ea5e9;
}

.exchanges-card .exchange-item.dex {
  background: #fef3c7;
  border-color: #f59e0b;
}

.exchanges-card .exchange-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.exchanges-card .exchange-details .fee-info {
  display: flex;
  gap: 16px;
  margin-bottom: 8px;
  font-size: 12px;
  color: #4b5563;
}

.exchanges-card .exchange-details .characteristics {
  display: flex;
  gap: 4px;
  flex-wrap: wrap;
}

/* 价格监控区域 */
.price-monitor-card .monitor-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.price-monitor-card .monitor-controls {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.price-monitor .symbol-section {
  margin-bottom: 32px;
}

.price-monitor .symbol-section:last-child {
  margin-bottom: 0;
}

.price-monitor .symbol-title {
  margin: 0 0 16px 0;
  font-size: 20px;
  font-weight: 600;
  color: #1f2937;
  text-align: center;
}

.price-monitor .exchanges-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 16px;
  margin-bottom: 20px;
}

.price-monitor .exchange-card {
  padding: 16px;
  border-radius: 12px;
  background: white;
  border: 2px solid #e5e7eb;
  transition: all 0.3s ease;
}

.price-monitor .exchange-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.price-monitor .exchange-card.highest {
  background: linear-gradient(135deg, #fee2e2 0%, #fecaca 100%);
  border-color: #ef4444;
}

.price-monitor .exchange-card.highest .main-price {
  color: #dc2626;
}

.price-monitor .exchange-card.lowest {
  background: linear-gradient(135deg, #dcfce7 0%, #bbf7d0 100%);
  border-color: #16a34a;
}

.price-monitor .exchange-card.lowest .main-price {
  color: #15803d;
}

.price-monitor .exchange-card.cex {
  border-left: 4px solid #0ea5e9;
}

.price-monitor .exchange-card.dex {
  border-left: 4px solid #f59e0b;
}

.price-monitor .exchange-card.dex .network {
  background: #fef3c7;
  color: #92400e;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 10px;
  margin-left: 8px;
}

.price-monitor .exchange-name {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
  font-size: 14px;
  font-weight: 600;
  color: #374151;
}

.price-monitor .price-info .main-price {
  font-size: 24px;
  font-weight: 700;
  color: #1f2937;
  margin-bottom: 8px;
}

.price-monitor .price-info .bid-ask {
  display: flex;
  justify-content: space-between;
  margin-bottom: 4px;
  font-size: 12px;
}

.price-monitor .price-info .bid {
  color: #16a34a;
  font-weight: 500;
}

.price-monitor .price-info .ask {
  color: #dc2626;
  font-weight: 500;
}

.price-monitor .price-info .spread {
  font-size: 11px;
  color: #6b7280;
  text-align: center;
  background: #f3f4f6;
  padding: 4px 8px;
  border-radius: 6px;
}

.price-monitor .volume {
  font-size: 12px;
  color: #6b7280;
  margin: 8px 0 4px 0;
}

.price-monitor .depth {
  font-size: 11px;
  color: #9ca3af;
}

/* 价格差异摘要 */
.price-diff-summary {
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
  border: 1px solid #e2e8f0;
  border-radius: 12px;
  padding: 16px;
}

.price-diff-summary .diff-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.price-diff-summary .diff-item:last-child {
  margin-bottom: 0;
}

.price-diff-summary .diff-item.important {
  background: #fef3c7;
  margin: -8px -12px 8px -12px;
  padding: 12px;
  border-radius: 8px;
  border: 1px solid #f59e0b;
}

.price-diff-summary .diff-item.important .label {
  font-weight: 600;
  color: #92400e;
}

.price-diff-summary .diff-item.important .value {
  font-weight: 700;
  color: #92400e;
}

.price-diff-summary .diff-item .label {
  font-size: 14px;
  color: #475569;
  font-weight: 500;
}

.price-diff-summary .diff-item .value {
  font-size: 14px;
  color: #1e293b;
  font-weight: 600;
}

.price-diff-summary .diff-explanation {
  margin-top: 8px;
  padding-top: 8px;
  border-top: 1px solid #e2e8f0;
}

.price-diff-summary .diff-explanation small {
  color: #64748b;
  font-size: 11px;
  line-height: 1.4;
}

/* 套利机会区域 */
.opportunities-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
}

.opportunities-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-controls {
  display: flex;
  gap: 10px;
  align-items: center;
}

.opportunities-list {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(450px, 1fr));
  gap: 20px;
  max-height: 600px;
  overflow-y: auto;
}

.opportunity-item {
  position: relative;
  padding: 20px;
  border-radius: 15px;
  background: linear-gradient(135deg, #fff 0%, #f8f9fa 100%);
  border: 2px solid #e9ecef;
  transition: all 0.3s ease;
}

.opportunity-item:hover {
  transform: translateY(-3px);
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
}

.opportunity-item.cex-cex {
  border-left: 4px solid #67c23a;
}

.opportunity-item.dex-dex {
  border-left: 4px solid #e6a23c;
}

.opportunity-item.cex-dex {
  border-left: 4px solid #f56c6c;
}

.opportunity-item.active {
  background: linear-gradient(135deg, #e8f5e8 0%, #f0f9ff 100%);
  border-color: #67c23a;
}

.opp-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.opp-title {
  display: flex;
  align-items: center;
  gap: 8px;
}

.opp-duration {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 12px;
  color: #666;
}

.opp-exchanges {
  margin-bottom: 15px;
}

.exchange-pair {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 15px;
  background: rgba(64, 158, 255, 0.05);
  border-radius: 10px;
  border: 1px solid rgba(64, 158, 255, 0.2);
}

.high-exchange, .low-exchange {
  flex: 1;
  text-align: center;
}

.high-exchange .price {
  color: #f56c6c;
  font-weight: bold;
  margin: 5px 0;
}

.low-exchange .price {
  color: #67c23a;
  font-weight: bold;
  margin: 5px 0;
}

.action {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 11px;
  font-weight: bold;
  margin-top: 5px;
}

.action.short {
  background: rgba(245, 108, 108, 0.2);
  color: #f56c6c;
}

.action.long {
  background: rgba(103, 194, 58, 0.2);
  color: #67c23a;
}

.arrow {
  font-size: 20px;
  color: #409eff;
  margin: 0 15px;
}

.opp-metrics {
  margin-bottom: 15px;
}

.metric-row {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 10px;
  margin-bottom: 10px;
}

.metric {
  text-align: center;
  padding: 8px;
  background: rgba(255, 255, 255, 0.7);
  border-radius: 6px;
}

.metric.important {
  background: rgba(64, 158, 255, 0.1);
  border: 1px solid rgba(64, 158, 255, 0.3);
}

.metric .label {
  display: block;
  font-size: 11px;
  color: #666;
  margin-bottom: 4px;
}

.metric .value {
  font-weight: bold;
  color: #2c3e50;
}

.cost-breakdown {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 8px;
  margin-bottom: 10px;
}

.cost-item {
  padding: 6px;
  background: rgba(230, 162, 60, 0.1);
  border-radius: 4px;
  font-size: 12px;
  text-align: center;
  color: #e6a23c;
}

.profit-analysis {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  background: rgba(103, 194, 58, 0.1);
  border-radius: 8px;
  margin-bottom: 10px;
}

.profit-analysis.negative {
  background: rgba(245, 108, 108, 0.1);
}

.profit-item .label {
  font-size: 12px;
  color: #666;
}

.profit-item .value {
  font-weight: bold;
  color: #67c23a;
  margin-left: 5px;
}

.profit-item.negative .value {
  color: #f56c6c;
}

.execution-time {
  font-size: 11px;
  color: #666;
}

.tags-section {
  margin-bottom: 15px;
}

.risks, .advantages {
  margin-bottom: 8px;
}

.risks strong, .advantages strong {
  font-size: 12px;
  margin-right: 8px;
}

.opp-actions {
  display: flex;
  gap: 8px;
}

.no-opportunities {
  grid-column: 1 / -1;
  text-align: center;
  padding: 40px;
}

/* 配置弹窗样式 */
.config-dialog-content {
  max-height: 70vh;
  overflow-y: auto;
}

.config-item {
  padding: 20px;
}

.config-header-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 15px;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border-radius: 10px;
}

.symbol-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.symbol-info .symbol {
  font-size: 18px;
  font-weight: bold;
  color: #2c3e50;
}

.config-sections {
  display: flex;
  flex-direction: column;
  gap: 25px;
}

.config-section {
  background: rgba(255, 255, 255, 0.8);
  padding: 20px;
  border-radius: 12px;
  border: 1px solid #e9ecef;
}

.config-section h4 {
  color: #2c3e50;
  margin-bottom: 15px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8px;
}

.config-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 15px;
}

.config-item-detail {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.config-item-detail label {
  font-weight: 500;
  color: #34495e;
  font-size: 14px;
}

.exchanges-config, .networks-config {
  margin-top: 15px;
}

.exchanges-config label, .networks-config label {
  display: block;
  font-weight: 500;
  color: #34495e;
  margin-bottom: 8px;
}

.exchanges-list, .networks-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.hybrid-exchanges {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  margin-top: 15px;
}

.exchange-group label {
  display: block;
  font-weight: 500;
  color: #34495e;
  margin-bottom: 8px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 操作记录样式 */
.operations-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
}

.operations-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.operations-list {
  max-height: 400px;
  overflow-y: auto;
}

.operation-item {
  padding: 15px;
  border-radius: 10px;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border: 1px solid #dee2e6;
  margin-bottom: 10px;
  transition: all 0.3s ease;
}

.operation-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.1);
}

.op-header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}

.op-header .symbol {
  font-weight: bold;
  color: #2c3e50;
}

.op-details {
  display: grid;
  gap: 10px;
}

.positions {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.position {
  padding: 6px 10px;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 6px;
  font-size: 12px;
  border: 1px solid #e9ecef;
}

.position .long {
  color: #67c23a;
  font-weight: bold;
}

.position .short {
  color: #f56c6c;
  font-weight: bold;
}

.op-summary {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  font-size: 12px;
}

.op-summary .profit {
  color: #67c23a;
  font-weight: bold;
}

.op-summary .loss {
  color: #f56c6c;
  font-weight: bold;
}

.op-time {
  font-size: 12px;
  color: #666;
}

.no-operations {
  text-align: center;
  padding: 40px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .arbitrage-page {
    padding: 10px;
  }
  
  .price-monitor .exchanges-grid {
    grid-template-columns: 1fr;
  }
  
  .opportunities-list {
    grid-template-columns: 1fr;
  }
  
  .config-grid {
    grid-template-columns: 1fr;
  }
  
  .hybrid-exchanges {
    grid-template-columns: 1fr;
  }
}

/* 自定义滚动条 */
.opportunities-list::-webkit-scrollbar,
.operations-list::-webkit-scrollbar,
.config-dialog-content::-webkit-scrollbar,
.exchanges-list::-webkit-scrollbar {
  width: 6px;
}

.opportunities-list::-webkit-scrollbar-track,
.operations-list::-webkit-scrollbar-track,
.config-dialog-content::-webkit-scrollbar-track,
.exchanges-list::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.opportunities-list::-webkit-scrollbar-thumb,
.operations-list::-webkit-scrollbar-thumb,
.config-dialog-content::-webkit-scrollbar-thumb,
.exchanges-list::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.opportunities-list::-webkit-scrollbar-thumb:hover,
.operations-list::-webkit-scrollbar-thumb:hover,
.config-dialog-content::-webkit-scrollbar-thumb:hover,
.exchanges-list::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 交易对指示器 */
.symbol-indicators {
  display: flex;
  gap: 8px;
  margin-bottom: 16px;
  padding: 8px;
  background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
  border-radius: 8px;
  flex-wrap: wrap;
}

.symbol-indicator {
  padding: 6px 12px;
  background: #ffffff;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 12px;
  font-weight: 500;
  color: #6b7280;
}

.symbol-indicator:hover {
  background: #f3f4f6;
  border-color: #9ca3af;
  color: #374151;
}

.symbol-indicator.active {
  background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
  border-color: #2563eb;
  color: #ffffff;
  box-shadow: 0 2px 8px rgba(59, 130, 246, 0.3);
}

/* 当前交易对监控 */
.current-symbol-monitor {
  background: #ffffff;
  border-radius: 8px;
  padding: 16px;
}

.current-symbol-monitor .symbol-title {
  margin: 0 0 16px 0;
  font-size: 20px;
  font-weight: 600;
  color: #1e293b;
  text-align: center;
  padding: 8px;
  background: linear-gradient(135deg, #f1f5f9 0%, #e2e8f0 100%);
  border-radius: 6px;
}

/* 策略交易所信息 */
.strategy-exchanges {
  margin: 16px 0;
  padding: 16px;
  background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
  border-radius: 8px;
  border: 1px solid #cbd5e1;
}

.strategy-exchanges h4 {
  margin: 0 0 12px 0;
  font-size: 14px;
  font-weight: 600;
  color: #1e293b;
}

.strategy-exchanges .exchanges-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 8px;
}

.strategy-exchange-item {
  background: #ffffff;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
  padding: 12px;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.strategy-exchange-item:hover {
  border-color: #cbd5e1;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.strategy-exchange-item.cex {
  border-left: 3px solid #10b981;
}

.strategy-exchange-item.dex {
  border-left: 3px solid #f59e0b;
}

.strategy-exchange-item .exchange-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 6px;
}

.strategy-exchange-item .exchange-header strong {
  font-size: 12px;
  color: #1e293b;
}

.strategy-exchange-item .exchange-details {
  font-size: 11px;
}

.strategy-exchange-item .fee-info {
  display: flex;
  gap: 8px;
  margin-bottom: 4px;
}

.strategy-exchange-item .fee-item {
  color: #6b7280;
  padding: 2px 4px;
  background: #f3f4f6;
  border-radius: 3px;
}

.strategy-exchange-item .characteristics {
  display: flex;
  gap: 4px;
  margin-bottom: 4px;
  flex-wrap: wrap;
}

.strategy-exchange-item .networks {
  display: flex;
  gap: 4px;
  align-items: center;
  flex-wrap: wrap;
}

.strategy-exchange-item .network-label {
  font-size: 10px;
  color: #9ca3af;
  font-weight: 500;
}

.strategy-analysis .best-practices {
  margin-top: 16px;
}

.strategy-analysis .best-practices h4 {
  margin: 0 0 8px 0;
  font-size: 14px;
  font-weight: 600;
  color: #7c3aed;
}

.strategy-analysis .best-practices ul {
  margin: 0;
  padding-left: 16px;
  font-size: 12px;
}

.strategy-analysis .best-practices li {
  margin-bottom: 4px;
  line-height: 1.4;
  color: #6366f1;
}

/* 历史套利机会区域 */
.history-opportunities-card .history-opportunities-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.history-opportunities-card .header-controls {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.history-opportunities-list {
  display: grid;
  grid-template-columns: 1fr;
  gap: 16px;
  max-height: 600px;
  overflow-y: auto;
}

.history-opportunity-item {
  background: #ffffff;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 12px;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.history-opportunity-item:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.history-opportunity-item.executed {
  border-left: 4px solid #10b981;
}

.history-opportunity-item.missed {
  border-left: 4px solid #f59e0b;
}

.history-opportunity-item.expired {
  border-left: 4px solid #6b7280;
}

/* 历史机会头部样式 */
.hist-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid #e5e7eb;
  flex-wrap: wrap;
  gap: 8px;
}

.hist-header .symbol {
  font-size: 16px;
  font-weight: 700;
  color: #1e293b;
  margin-right: 8px;
}

.hist-header .duration {
  font-size: 12px;
  color: #6b7280;
  background: #f3f4f6;
  padding: 2px 8px;
  border-radius: 12px;
  margin-left: auto;
}

/* 历史机会详情样式 */
.hist-details {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.hist-details .profit-comparison {
  display: flex;
  justify-content: space-between;
  gap: 12px;
  padding: 8px 12px;
  background: #f8fafc;
  border-radius: 6px;
  margin-bottom: 8px;
}

.hist-details .potential-profit,
.hist-details .actual-profit {
  text-align: center;
  flex: 1;
}

.hist-details .potential-profit .profit,
.hist-details .actual-profit .profit {
  color: #059669;
  font-weight: 600;
}

.hist-details .actual-profit .loss {
  color: #dc2626;
  font-weight: 600;
}

.hist-details .price-info {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 6px 8px;
  background: #f9fafb;
  border-radius: 4px;
  font-size: 14px;
  flex-wrap: wrap;
}

.hist-details .price-info .arrow {
  color: #3b82f6;
  font-weight: bold;
}

.hist-details .price-info .spread {
  color: #7c3aed;
  font-weight: 600;
  margin-left: 8px;
}

.history-opp-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  flex-wrap: wrap;
  gap: 8px;
}

.history-opp-header .opp-basic-info {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.history-opp-header .symbol {
  font-size: 16px;
  font-weight: 600;
  color: #1e293b;
}

.history-opp-header .opp-time-info {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  font-size: 12px;
  color: #6b7280;
  gap: 2px;
}

.history-opp-content {
  margin-bottom: 12px;
}

.history-opp-content .exchanges-info {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
  padding: 12px;
  background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
  border-radius: 8px;
}

.history-opp-content .exchange-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
}

.history-opp-content .exchange-name {
  font-weight: 600;
  color: #1e293b;
}

.history-opp-content .exchange-type {
  font-size: 12px;
  color: #6b7280;
}

.history-opp-content .price-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 2px;
}

.history-opp-content .price {
  font-size: 14px;
  font-weight: 600;
  color: #374151;
}

.history-opp-content .action {
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 4px;
  font-weight: 500;
}

.history-opp-content .action.long {
  background: #dcfce7;
  color: #166534;
}

.history-opp-content .action.short {
  background: #fee2e2;
  color: #991b1b;
}

.history-opp-content .arrow {
  font-size: 24px;
  color: #3b82f6;
}

.profit-analysis {
  background: #ffffff;
  border-radius: 8px;
  padding: 12px;
  margin-bottom: 12px;
}

.profit-metrics {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 12px;
  margin-bottom: 12px;
}

.profit-metrics .metric {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.profit-metrics .label {
  font-size: 12px;
  color: #6b7280;
  font-weight: 500;
}

.profit-metrics .value {
  font-size: 14px;
  font-weight: 600;
  color: #374151;
}

.profit-metrics .value.important {
  color: #3b82f6;
}

.profit-metrics .value.positive {
  color: #059669;
}

.profit-metrics .value.negative {
  color: #dc2626;
}

.profit-metrics .value.missed {
  color: #f59e0b;
}

.execution-details {
  border-top: 1px solid #e5e7eb;
  padding-top: 12px;
}

.executed-info, .missed-info, .expired-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.execution-result {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
}

.execution-details-breakdown {
  display: flex;
  gap: 16px;
  font-size: 12px;
  color: #6b7280;
  flex-wrap: wrap;
}

.execution-success-rate {
  font-size: 12px;
  color: #059669;
  font-weight: 500;
}

.missed-reason, .expired-reason {
  display: flex;
  gap: 8px;
  align-items: center;
}

.missed-loss {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.history-tags {
  margin-bottom: 12px;
}

.history-tags .risk-tags,
.history-tags .performance-tags {
  display: flex;
  gap: 8px;
  align-items: center;
  margin-bottom: 8px;
  flex-wrap: wrap;
}

.history-tags .label {
  font-size: 12px;
  color: #6b7280;
  font-weight: 500;
  min-width: 60px;
}

/* 历史机会详细信息样式 */
.additional-info {
  margin: 12px 0;
  padding: 8px 12px;
  background: #f8fafc;
  border-radius: 6px;
  border-left: 3px solid #3b82f6;
}

.additional-info > div {
  font-size: 13px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 2px 0;
  margin-bottom: 2px;
}

.additional-info > div:last-child {
  margin-bottom: 0;
}

.additional-info .profit {
  color: #059669;
  font-weight: 600;
}

.additional-info .loss {
  color: #dc2626;
  font-weight: 600;
}

.risk-factors {
  margin-top: 8px;
  padding: 6px 0;
}

.risk-factors .label {
  display: inline-block;
  font-size: 12px;
  color: #6b7280;
  font-weight: 500;
  margin-right: 8px;
  margin-bottom: 4px;
}

.risk-factors .el-tag {
  margin-right: 4px;
  margin-bottom: 4px;
}

.hist-time {
  margin-top: 8px;
  font-size: 12px;
  color: #6b7280;
  display: flex;
  align-items: center;
  gap: 6px;
  flex-wrap: wrap;
}

.missed-reason, .expired-reason {
  color: #f59e0b;
  font-weight: 500;
}

.history-opp-actions {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
  flex-wrap: wrap;
}

.no-history-opportunities {
  text-align: center;
  padding: 40px 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .arbitrage-page {
    padding: 10px;
  }
  
  .price-monitor .exchanges-grid {
    grid-template-columns: 1fr;
  }
  
  .opportunities-list {
    grid-template-columns: 1fr;
  }
  
  .config-grid {
    grid-template-columns: 1fr;
  }
  
  .hybrid-exchanges {
    grid-template-columns: 1fr;
  }
}
</style> 